var express = require('express');
var router = express.Router();
var request = require('request');
const cheerio = require('cheerio');
const _ = require('lodash');
const Models = require('../unit/Models');

const catchFirstUrl = 'http://music.163.com/discover/playlist/',	//入口页面
	urlsArray = [],	//存放爬取网址
	catchDate = [],	//存放爬取数据
	pageUrls = [],	//存放收集文章页面网站
	limit = 35,	// 分页
  offset = 0, // 分页
  maxPage = 1, // 目前最大页数
	startDate = new Date(),	//开始时间
	endDate = false;	//结束时间
	songCount = 0;
	playCount = 0;
const playUrl = 'http://music.163.com/playlist?id='; // 歌单详情
for(var i = 0 ; i< maxPage ; i++){
	pageUrls.push(`http://223.252.199.66/discover/playlist/?limit=35&offset=${i * limit}`);
}
function requestP (url) {
   return new Promise((resolve, reject) => {
    request(url, (error, response, body) => {
      if (!error && response.statusCode == 200) {
        data = body;
        return resolve(body);
      } else {
				console.log(error);
			}
      return reject(error);
    })
  });
}

/* GET home page. */
router.get('/', async function(req, res, next) {
	let count = 0;
  let promises = pageUrls.map(async (url, index) => {
		console.log(url);
    const data = await requestP(url);
    const $ = cheerio.load(data);
    const list = [];
    $('#m-pl-container li').map(async function (i, el) {
      const $li = $(this);
      const item = {
        imgUrl: $li.find('.u-cover').find('img').attr('src').split("?")[0],
        title: $li.find('.tit').text(),
        id: $li.find('.u-cover').find('.bottom .icon-play').attr('data-res-id'),
        type: $li.find('.u-cover').find('.bottom .icon-play').attr('data-res-type'),
        playNum: $li.find('.u-cover').find('.bottom .nb').text(),
        author: $li.find('p a.nm').text(),
        authorId: $li.find('p a.nm').attr('href').split("?")[1].split('=')[1],
      };
      list.push(item);
			// 获取歌单中
			// const detail = await getDetail(item.id);
			const itemDetail = Object.assign({}, item);
			Models.PlayList.update({id: item.id}, itemDetail, { upsert: true }, (err, docs) => {
		    if(err) console.log(err);
				playCount ++;
				console.log(playCount);
			});
			// detail.songs.map((item, i) => {
			// 	Models.Song.update({id: item.id}, item, { upsert: true }, (err, docs) => {
			// 	 if(err) console.log(err);
 		// 		 songCount ++;
 		// 		 console.log(songCount);
 		// 	 });
			// });
    });
    return Promise.resolve(list);
  });
  const results = await Promise.all(promises);
  const playList = _.chain(results)
    .flatten(true)
    .uniq('id');
  res.send(playList);
});
function getDetail (id) {
	return new Promise((resolve, reject) => {
		const url = `${playUrl}${id}`;
		request(url, (error, response, body) => {
		 if (!error && response.statusCode == 200) {
			 const $ = cheerio.load(body);
			 let detail = {
				 desc: $('#album-desc-more').html(),
				 collectNum: $('#content-operation .u-btni-fav').attr('data-count'),
				 shareNum: $('#content-operation .u-btni-share').attr('data-count'),
				 commentNum: $('#cnt_comment_count').text(),
				 tags: [],
				 playNum: $('#play-count').text(),
				 songs: [],
				 songIds: [],
			 }
			 if (!!$('#song-list-pre-cache textarea').eq(0)) {
				let songs = [];
				try {
					songs = JSON.parse($('#song-list-pre-cache textarea').eq(0).val());
				} catch (e) {
					console.log(e);
				}
				detail.songs = songs;
				detail.songIds = songs.map(item => {
					return item.id;
				});
			 }
			 $('.tags.f-cb .u-tag i').each(function (i, elem) {
				 detail.tags[i] = $(this).text();
			 });
			 return resolve(detail);
		 }
		 return reject(error);
	 });
 });
};

module.exports = router;
